package com.yzh.sharding.config;

import cn.hutool.core.lang.ClassScaner;
import com.google.common.collect.Maps;
import com.yzh.sharding.annotation.HandlerType;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @program: yzh->HanderProcessor
 * @description: 自定义处理器
 * @author: yangzhanghui
 * @create: 2019-11-29 15:13
 **/
@Component
public class HanderProcessor implements BeanFactoryPostProcessor {

    private static final String HANDLER_PACKAGE = "com.yzh.sharding.service.impl";

    /*
    * 扫描@HandlerType,初始化HandlerContext,将其注册到spring容器
    *
    * @param beanFactory    bean工厂
    * @see HandlerType
    * @see HandlerContext
    * */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map<Integer, Class> handlerMap = Maps.newHashMapWithExpectedSize(3);
        ClassScaner.scanPackageByAnnotation(HANDLER_PACKAGE, HandlerType.class).forEach(clazz -> {
            int type = clazz.getAnnotation(HandlerType.class).value();
            handlerMap.put(type, clazz);
        });

        HandlerContext context = new HandlerContext(handlerMap);
        beanFactory.registerSingleton(HandlerContext.class.getName(), context);
    }
}
